<?php

namespace App\Admin\Controllers;

use Encore\Admin\Layout\Content;
use Carbon\Carbon;
use App\Models\Product;
use App\Models\SeckillProduct;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Show;
use Encore\Admin\Controllers\AdminController;

class SeckillProductsController extends AdminController
{
    protected $title = '秒杀商品';
    
    protected function grid()
    {
        $grid = new Grid(new SeckillProduct());
	    $grid->model()->orderByDesc('saled_at');
	    $grid->disableExport();
	    
	    $grid->column('id', 'ID');
        $grid->column('product_id', '商品')->display(function () {
	        return isset($this->product) ? "{$this->product->id}: {$this->product->title}" : '';
        });
        $grid->column('product_price', '商品价格')->display(function () {
            return isset($this->product->skus) ? "{$this->product->skus->first()->price_vip}" : '';
        });
        $grid->column('seckill_count', '当前秒杀商品数量');
        $grid->column('seckill_count_all', '分配秒杀商品数量');
        $grid->column('quota', '限购数量');

        
	    $grid->column('saled_at', '上架时间')->display(function () {
	    	return $this->saled_at;
	    });
        $grid->column('created_at', '创建时间')->display(function () {
            return $this->created_at->toDatetimeString();
        });
        $this->gridFilter($grid);
        return $grid;
    }
    
    protected function detail($id)
    {
        $show = new Show(SeckillProduct::findOrFail($id));

        return $show;
    }

     protected function gridFilter(Grid $grid)
    {
        $grid->filter(function (Grid\Filter $filter) {
            $filter->expand();

            
            $filter->equal('product_id', '商品查询')->select(Product::where("is_seckill",true)->get()->pluck('title', 'id'));

          

           
        });
    }

    
    protected function form()
    {
        $form = new Form(new SeckillProduct());
		$form->select('product_id','商品')->options(Product::where("is_seckill",true)->get()->pluck('title', 'id'));
        $form->text('seckill_count', '秒杀商品数量')->default(1);
        $form->text('quota', '限购数量')->default(0);
        $form->date('saled_at', '上架时间');  
        $this->formSaved($form);

        return $form;
    }

    protected function formSaved(Form $form)
    {
        $form->saved(function (Form $form) {
            $form->model()->update(['seckill_count_all'=> $form->seckill_count]);
           
        });
    }

   
  
}
